package com.pocketmenu.business;

import java.text.DecimalFormat;

import com.pocketmenu.persistence.SQLiteHelper;
import com.pocketmenu.ui.R;


import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;


public class ItemListCursorAdapter extends SimpleCursorAdapter {
	
	private int layout;
	private OnTouchListener listener;
	
	@SuppressWarnings("deprecation")
	public ItemListCursorAdapter(Context context, int layout, Cursor c,
			String[] from, int[] to, OnTouchListener listener) {
		super(context, layout, c, from, to);
		this.layout = layout;
		this.listener = listener;
	}
	
	@Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {

        Cursor c = getCursor();

        final LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(layout, parent, false);        
        v.setOnTouchListener(listener);        
        
        return bindValues(v, context, c);
    }
	
	private View bindValues(View v, Context context, Cursor c)
	{
		int descriptionIndex = c.getColumnIndex(SQLiteHelper.COLUMN_ITEM_DESCRIPTION);
    	int nameIndex = c.getColumnIndex(SQLiteHelper.COLUMN_ITEM_NAME);
    	int priceIndex = c.getColumnIndex(SQLiteHelper.COLUMN_ITEM_PRICE);
    	int recomendedIndex = c.getColumnIndex(SQLiteHelper.COLUMN_ITEM_RECOMENDED);
    	
        String description = c.getString(descriptionIndex);
        String name = c.getString(nameIndex);
        int price = c.getInt(priceIndex);
        boolean recomended = c.getInt(recomendedIndex) != 0;
        
        TextView tvItemDescriptionTemp = (TextView) v.findViewById(R.id.tvItemDescription);
        if (tvItemDescriptionTemp != null) {
        	if(description.length() > 40)
        		tvItemDescriptionTemp.setText(description.substring(0, 36) + " ...");
        	else
        		tvItemDescriptionTemp.setText(description);
        }

        TextView tvItemNameTemp = (TextView) v.findViewById(R.id.tvItemName);
        if (tvItemNameTemp != null) {
        	tvItemNameTemp.setText(name);
        }
        
        TextView tvItemPrice = (TextView) v.findViewById(R.id.tvItemPrice);
        if (tvItemPrice != null) {            
        	DecimalFormat df = new DecimalFormat("#,###,###");
        	tvItemPrice.setText("$" + df.format(price));
        }
        
        ImageView imgStar = (ImageView) v.findViewById(R.id.imgStar);
        if(imgStar != null)
        {
        	if(!recomended)
        	{
        		imgStar.setVisibility(View.GONE);
        	}
        }
        return v;
	}
	
    @Override
    public void bindView(View v, Context context, Cursor c) {
    	
    	bindValues(v, context, c);
    }           
	
}
